package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.LoginDto;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private HttpServletRequest request;

    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody LoginDto loginDto) {
        //生成六位验证码
        String code = ValidateCodeUtils.generateValidateCode4String(6);
        System.out.println(code);
        //通过阿里云发送短信
        //SendSms.sendMsg(loginDto.getPhone(), code);
        //将生成的随机数存入session
        HttpSession session = request.getSession();
        session.setAttribute(loginDto.getPhone(), code);
        return R.success("发送成功");
    }

    @PostMapping("/login")
    public R login(@RequestBody LoginDto loginDto) {
        if (loginDto == null) {
            return R.error("参数错误");
        }

        HttpSession session = request.getSession();
        String code = (String) session.getAttribute(loginDto.getPhone());

        if (code == null) {
            return R.error("请先获取验证码");
        }
        if (!code.equals(loginDto.getCode())) {
            return R.error("验证码错误");
        }

       User user = userService.findByPhone(loginDto.getPhone());

        if (user==null){
           User newUesr = userService.addUser(loginDto.getPhone());
           session.setAttribute("userId",newUesr.getId());
           return R.success("登录成功");
        }

        session.setAttribute("userId",user.getId());
        return R.success("登录成功");
    }
    @PostMapping("/loginout")
    public R loginout(){
        //清除用户session
        HttpSession session = request.getSession();
        session.invalidate();

        return R.success("退出成功");
    }
}
